package com.dubbo.study.utils;

import java.security.MessageDigest;

/**
 * @program: dubbostudy
 *
 * @description:
 *
 * @author: heqiang
 *
 * @create: 2019-10-23 17:19
 **/
public class MD5Utils {


    private static final String[] hexDigIts = {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};



    public static String MD5Encode(String str,String charSet) {
        String result = null;
        if(StringUtil.isEmpty(str)){
            return result;
        }
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            if(StringUtil.isEmpty(charSet)){
                result = byteArrayToHex(str.getBytes());
            } else {
                result = byteArrayToHex(md.digest(str.getBytes(charSet)));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    public static String byteArrayToHex(byte[] bytes) {
        StringBuffer result = new StringBuffer();
        for (int i = 0;i<bytes.length;i++) {
            result.append(byteToHex(bytes[i]));
        }
        return result.toString();
    }

    public static String byteToHex (byte b) {
        int n = b;
        if (n < 0) {
            n += 256;
        }
        int n1 = n / 16;
        int n2 = n % 16;
        return hexDigIts[n1] + hexDigIts[n2];
    }

}
